import axios from 'axios';
import router from '@/routers/index.js'; // 引入路由实例
import { useAuthStore } from '@/stores/auth'; // 引入Pinia store
import { ElMessage } from 'element-plus';
import config from "@/config.js"; // 引入ElMessage

// 创建axios实例
const service = axios.create({
    baseURL: config.apiBaseUrl,
    timeout: 15000, // 延长超时时间
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
        // 'Content-Type':'application/x-www-form-urlencoded'
    },
    withCredentials: true // 如果需要跨域携带cookie
});

// 请求拦截器
service.interceptors.request.use(
    config => {
        const authStore = useAuthStore();

        // 添加JWT token
        if (authStore.token) {
            config.headers['Authorization'] = `${authStore.token}`;
        }

        // 如果是文件上传，修改Content-Type
        if (config.data instanceof FormData) {
            config.headers['Content-Type'] = 'multipart/form-data';
        }

        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    response => {
        // 直接返回响应数据
        console.log(response.data)
        if (response.data.code !== 200) {
            showError(response.data.msg);
            return Promise.reject(response.data);

        }
        return response.data;

    },
    async error => {
        const authStore = useAuthStore();
        const originalRequest = error.config;
        console.log(error.response)
        // 处理HTTP错误状态码
        if (error.response) {
            switch (error.response.code) {
                case 400:
                    showError(getErrorMessage(error.response));
                    break;
                case 401:
                    // token过期，尝试刷新token
                    if (!originalRequest._retry && authStore.refreshToken) {
                        originalRequest._retry = true;
                        try {
                            const { token } = await authStore.refreshToken();
                            originalRequest.headers['Authorization'] = `Bearer ${token}`;
                            return service(originalRequest);
                        } catch (refreshError) {
                            authStore.logout();
                            router.push('/login');
                            showError('刷新Token失败，请重新登录', refreshError);
                            return Promise.reject(refreshError);
                        }
                    } else {
                        authStore.logout();
                        router.push('/login');
                        showError('请重新登录');
                    }
                    break;
                case 403:
                    router.push('/forbidden');
                    showError('无权限访问此页面');
                    break;
                case 404:
                    router.push('/not-found');
                    showError('请求地址不存在');
                    break;
                case 500:
                    router.push('/server-error');
                    showError('服务器内部错误');
                    break;
                default:
                    const errorMessage = getErrorMessage(error.response);
                    showError(errorMessage);
            }

            return Promise.reject({
                status: error.response.status,
                message: getErrorMessage(error.response),
                data: error.response.data
            });
        }

        // 网络错误处理
        if (error.message.includes('timeout')) {
            showError('请求超时，请检查网络连接');
        } else if (error.message.includes('Network Error')) {
            showError('网络错误，请检查网络连接');
        }

        return Promise.reject(error);
    }
);

function showError(message, error) {
    ElMessage({
        message: message,
        type: 'error',
        duration: 5 * 1000, // 显示5秒
    });
}

function getErrorMessage(response) {
    return response.data?.message ||
        response.data?.error ||
        '请求失败，请稍后重试';
}

export default service;